package com.demo.bean;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.HashMap;
import java.util.LinkedList;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;


/**
 * @author gatts, 2020/11/7 17:48
 */
public class MockitoTest {

    @Mock
    LinkedList<String> mockLinkedList;
    @Mock
    HashMap<String, String> mockMap;

    public MockitoTest() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    public void test1(){
        //- 创建mock对象
        // 使用@Mock注解声明方式解决泛型问题
         LinkedList<String> linkedList = mock(LinkedList.class);
        //- 设定预期返回值
        when(linkedList.get(0)).thenReturn("hello");
        when(linkedList.get(1)).thenReturn("world");
        when(linkedList.get(2)).thenThrow(new RuntimeException());
        //- 调用

        Assertions.assertEquals(linkedList.get(0), "hello");
        Assertions.assertEquals(linkedList.get(1), "world");
        Assertions.assertThrows(RuntimeException.class, () -> linkedList.get(2));
    }

    @Test
    public void test2(){
        HashMap map = mock(HashMap.class);
        //- 构造mock，put任意键值均返回“haha”
        when(map.put(any(), any())).thenReturn("haha");
        Object val = map.put("key-x", "bingo");
        Assertions.assertEquals("haha", val);
        System.out.println(val);
    }

}
